package com.lunkr.demo;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class SurpriseLayout extends LinearLayout {

    private WebView webView;

    private TextView progressTv;

    private TextView titleTv;

    private String mTitleStr;

    private ChangeTitle mChangeTitle;

    public void setChangeTitle(ChangeTitle mChangeTitle) {
        this.mChangeTitle = mChangeTitle;
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public SurpriseLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    public SurpriseLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public SurpriseLayout(Context context) {
        super(context);
        init(context);
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void init(Context context) {
//        setBackgroundResource(R.color.main_bg_color);
        setOrientation(VERTICAL);

        //网页布局
        FrameLayout bodyFl = new FrameLayout(context);
        LayoutParams lpBody = new LayoutParams(LayoutParams.MATCH_PARENT, 0);
        lpBody.weight = 1;
        bodyFl.setLayoutParams(lpBody);
        addView(bodyFl);

        RelativeLayout llBody = new RelativeLayout(context);
        llBody.setLayoutParams(new FrameLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        bodyFl.addView(llBody);

        progressTv = new TextView(context);
        progressTv.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                5));
        progressTv.setBackgroundColor(0xFF33FF33);
        progressTv.setVisibility(GONE);

        webView = new WebView(context);
        RelativeLayout.LayoutParams webParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT);
        webView.setLayoutParams(webParams);

        WebSettings settings = webView.getSettings();
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
//        webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY);//设置 缓存模式
        settings.setDomStorageEnabled(true);// 开启 DOM storage API 功能
        settings.setDatabaseEnabled(true);//开启 database storage API 功能
        String cacheDirPath = context.getFilesDir().getAbsolutePath() + "/webcache";

        settings.setDatabasePath(cacheDirPath);//设置数据库缓存路径
        settings.setAppCachePath(cacheDirPath);//设置  Application Caches 缓存目录
        settings.setAppCacheEnabled(true);//开启 Application Caches 功能
        settings.setJavaScriptEnabled(true);

        settings.setAllowFileAccessFromFileURLs(true);
        settings.setAllowUniversalAccessFromFileURLs(true);
        settings.setAllowFileAccess(true);
        settings.setAllowContentAccess(true);





//                .cm.setAcceptFileSchemeCookies(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);//开启Https 支持含内嵌https资源
        }
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        } else {
            settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        }
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

        final int sWidth = getWidth(context);

        WebChromeClient client = new WebChromeClient() {
            //处理加载进度
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                RelativeLayout.LayoutParams lpProgress = (RelativeLayout.LayoutParams) progressTv.getLayoutParams();
                lpProgress.width = sWidth * newProgress / 100;
                progressTv.setLayoutParams(lpProgress);
                String title = webView.getTitle() != null ? webView.getTitle().trim() : null;
                if (!TextUtils.isEmpty(title)) {
                    if (!title.equals(mTitleStr)) {
                        mTitleStr = title;
                        if (mChangeTitle != null) {
                            mChangeTitle.onChangeTitle(mTitleStr);
                        }
                    }
                }
                if (newProgress > 0 && newProgress < 100) {
                    progressTv.setVisibility(VISIBLE);
                }
                else {
                    progressTv.setVisibility(GONE);
                }
            }
        };
        webView.setWebChromeClient(client);

        llBody.addView(webView);
        llBody.addView(progressTv);

        LinearLayout llShadow = new LinearLayout(context);
//        llShadow.setBackgroundResource(R.color.main_bg_color);
        llShadow.setLayoutParams(new FrameLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        bodyFl.addView(llShadow);
    }

    public int getWidth(Context context) {
        if (context instanceof Activity) {
            DisplayMetrics displaysMetrics = new DisplayMetrics();
            ((Activity) context).getWindowManager()
                    .getDefaultDisplay()
                    .getMetrics(displaysMetrics);

            //得到屏幕宽
            return displaysMetrics.widthPixels;
        }
        return 0;
    }


    public WebView getWebView() {
        return webView;
    }

    public TextView getProgressTv() {
        return progressTv;
    }

    public interface ChangeTitle{
        void onChangeTitle(String title);
    }
}
